package com.googlecode.continuity.core.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.ui.RootPanel;

/**
 * A UIEntryPoint is the abstract super class for all UI modules that can be injected into a host page.  When a host
 * page sets a UIEntryPoints to be loaded, its {@link UIEntryPoint#onModuleLoadUI()} method is called.  This class takes
 * care of bootstrapping the UIEntryPoint to the host page.
 * <p/>
 * To call a UIEntryPoint on the host page, make sure the GWTExternal javascript is available and call its
 * <code>addEntryPoint</code> method with the fully qualified type name of the entry point. For example:
 * <p/>
 * <code>GWTExternal.addEntryPoint("com.googlecode.continuity.plugin.project.client.MilestoneSearch");</code>
 *
 * @author Peter Schmitt <aragos@aragos.de>
 */
public abstract class UIEntryPoint implements EntryPoint {
  private String[] containers;

  /**
   * Explicit default constructor.
   */
  public UIEntryPoint() {
  }

  /**
   * Constructs a UIEntryPoint which will only be called if for every string in the containers array an element exists
   * on the host page which has an id equaling this string.
   *
   * @param containers
   */
  protected UIEntryPoint(String[] containers) {
    this.containers = containers;
  }

  /**
   * Bootstraps this UIEntryPoint with the host page, checking whether it is activated and making sure all required
   * containers are available.  If all contions are met fires the {@link UIEntryPoint#onModuleLoadUI()} method.
   */
  public final void onModuleLoad() {
    if (!GWTExternal.isEntryPointEnabled(GWT.getTypeName(this))) {
      return;
    }

    // check containers
    if (containers != null) {
      for (int i = 0; i < containers.length; i++) {
        if (RootPanel.get(containers[i]) == null) {
          return;
        }
      }
    }

    onModuleLoadUI();
  }

  protected abstract void onModuleLoadUI();
}
